package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.BankMessage;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 我的银行卡
 * 
 * @author mty
 * 
 */
public class MyBlockActivity extends BaseActivity implements OnClickListener {

	private final int RELIEVEBANK_CODE_ZERO = 3; // 解绑卡code=0
	private final int CLOSE_PROGRESSDIALOG = 5; // 关闭progressdialog
	private final int RELIEVEBANK_CODE_ELSE = 4; // 解绑卡code=其它
	// private String version; // 手机当前版本号
	private List<BankMessage> mList; // 我的银行卡数据源
	private RelativeLayout myblock_top_img; // 后退
	private Button unwrap_bt; // 　解除绑定
	private TextView block_name; // 卡名
	private ImageView bank_icon; // 图标
	private RelativeLayout block_top; // 卡背景
	private TextView card_numbertv; // 卡号
	private TextView card_number;
	private TextView hint_tv;
	private int statusCode;
	private String relieveDesc;
	private Dialog loadDialog;
	private Dialog mDialog;
	private Dialog alertDialog;
	DecimalFormat df = new DecimalFormat("###,###");
	private RelativeLayout support;
	private RelativeLayout nonAbnormal_rl; // 有数据界面（非异常界面）
	private RelativeLayout abnormal_rl; // 无网络或服务器异常（异常界面）
	private TextView abnormalCue_tv; // 数据异常提示语
	private boolean firstEntryFlag = true; // 第一次进入做界面异常判断

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_block);
		initView();
		setListener();
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				uiExceptionHandling(false, "");
				if (mList == null || mList.size() == 0) {
					finish();
				} else {
					String bankname = mList.get(0).getBankName();
					if ("农业银行".equals(bankname)) {
						block_top
								.setBackgroundResource(R.drawable.bank_agriculture);
					} else if ("建设银行".equals(bankname)) {
						block_top
								.setBackgroundResource(R.drawable.bank_business);
					} else if ("浙商银行".equals(bankname)) {
						block_top
								.setBackgroundResource(R.drawable.bank_construction);
					} else if ("招商银行".equals(bankname)) {
						block_top
								.setBackgroundResource(R.drawable.bankcard_bg_cmb);
					}
					ImageLoader.getInstance().displayImage(
							mList.get(0).getAppImageUrl(), bank_icon);
					block_name.setText(mList.get(0).getBankName());
					card_numbertv.setText("**** **** **** ");
					card_number.setText(mList.get(0).getCardNo()
							.substring(mList.get(0).getCardNo().length() - 4));
					PreferenceUtils.getInstance().setCardNo(
							BaseApplication.getInstance(),
							mList.get(0).getCardNo());
					// String limit = mList.get(0).getLimit();
					// LogUtil.e("limit", limit);
					// try {
					// String[] limits = limit.split("@");
					// String[] quota = limits[1].split("/");
					// hint_tv.setText(bankname + "提现限额\n单笔最多："
					// + df.format(Double.parseDouble(quota[0]))
					// + "元 | 每日最多："
					// + df.format(Double.parseDouble(quota[1])) + "元");
					// } catch (Exception e) {
					// hint_tv.setText("根据新浪方面的协议,本卡只限于提现,无法进行充值操作.");
					// }
					String limitInfo2 = mList.get(0).getLimitInfo2();
					hint_tv.setText(bankname + "充值限额\n" + limitInfo2);
				}
				break;
			case 2:
				statusCode = (Integer) msg.obj;
				if (statusCode == KkdHttpClient.NO_NET) {
					uiExceptionHandling(true, "网络错误，请稍后重试");
				} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
					uiExceptionHandling(true, "服务异常，请稍后重试");
				}
				break;
			case RELIEVEBANK_CODE_ZERO:
				showToast(R.string.unwrap_ok);

				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						finish();
					}
				}, 2100);
				break;
			// case RELIEVEBANK_CODE_ELSE:
			// String desc = (String) msg.obj;
			// showDialog1("解绑失败原因：" + desc);
			// break;
			case CLOSE_PROGRESSDIALOG:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				break;
			default:
				break;
			}

		};
	};

	/**
	 * 初始化控件
	 */
	@SuppressLint("ResourceAsColor")
	public void initView() {
		unwrap_bt = (Button) this.findViewById(R.id.unwrap_bt);
		myblock_top_img = (RelativeLayout) this
				.findViewById(R.id.myblock_top_img);
		block_name = (TextView) this.findViewById(R.id.block_name);
		bank_icon = (ImageView) this.findViewById(R.id.bank_icon);
		block_top = (RelativeLayout) this.findViewById(R.id.block_top);
		card_numbertv = (TextView) this.findViewById(R.id.card_numbertv);
		card_number = (TextView) this.findViewById(R.id.card_number);
		hint_tv = (TextView) this.findViewById(R.id.hint_tv);
		support = (RelativeLayout) this.findViewById(R.id.support);
		nonAbnormal_rl = (RelativeLayout) this
				.findViewById(R.id.nonAbnormal_rl);
		abnormal_rl = (RelativeLayout) this.findViewById(R.id.abnormal_rl);
		abnormalCue_tv = (TextView) this.findViewById(R.id.abnormalCue_tv);

	}

	/**
	 * 注册监听事件
	 */
	public void setListener() {
		unwrap_bt.setOnClickListener(this);
		myblock_top_img.setOnClickListener(this);
		support.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.myblock_top_img: // 后退
			finish();
			break;
		case R.id.unwrap_bt:
			SystemUtils.onEvent("Account_BankCard_RemoveCard", 1);
			showDialog("是否确定解绑银行卡?");
			break; // 解绑
		case R.id.support: // 支持银行卡
			Intent intent2 = new Intent(MyBlockActivity.this,
					KKDWebActivity.class);
			intent2.putExtra("url", com.kkd.kkdapp.Environment.getH5Url()
					+ "bankcard.html"); // 正式
			intent2.putExtra("useTitleName", true);
			intent2.putExtra("titleName", "支持的银行卡");
			startActivity(intent2);
			break;
		}
	}

	/**
	 * 银行卡列表
	 */
	public void myBankList() {
		KkdHttpMagager.getInstance().getMyBankManager(
				new TypeToken<List<BankMessage>>() {
				}.getType(), new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mList = (List<BankMessage>) responseBody;
						handler.sendEmptyMessage(1);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = 2;
						msg.obj = statusCode;
						handler.sendMessage(msg);
					}
				});

	}

	/******
	 * 数据异常界面处理
	 *****/
	public void uiExceptionHandling(boolean uiEp, String strEp) {
		if (uiEp) {
			if (firstEntryFlag) {
				nonAbnormal_rl.setVisibility(View.GONE);
				abnormal_rl.setVisibility(View.VISIBLE);
				abnormalCue_tv.setText(strEp);
				firstEntryFlag = false;
			}
		} else {
			firstEntryFlag = false;
			nonAbnormal_rl.setVisibility(View.VISIBLE);
			abnormal_rl.setVisibility(View.GONE);
		}
	}

	public void showDialog(String dialogTitle) {

		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.deleteBankDialog(this, dialogTitle,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.confirm_deletebank:
							if (mList != null) {
								String cardId = mList.get(0).getCardId();
								LogUtil.e("cardId", cardId);
								relieveBank(cardId);
							} else {
								if (statusCode == KkdHttpClient.NO_NET) {
									AppUtil.makeToastForCustomer(
											MyBlockActivity.this, "网络错误，请稍后重试");
								} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
									AppUtil.makeToastForCustomer(
											MyBlockActivity.this, "服务异常，请稍后重试");
								}
							}
							mDialog.dismiss();
							break;
						case R.id.cancel_deletebank:
							mDialog.dismiss();
							break;
						}
					}
				});
		mDialog.show();
	}

	public void showDialog1() {
		if (alertDialog != null) {
			alertDialog.cancel();
			alertDialog = null;
		}
		// alertDialog = DialogUtils.addBankDialog(this, dialogTitle,
		// new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// alertDialog.dismiss();
		// }
		// });
		alertDialog = DialogUtils.deleteBankCardFail(MyBlockActivity.this);
		alertDialog.show();
		/*
		 * AlertDialog.Builder builder = new AlertDialog.Builder(this);
		 * builder.setMessage(dialogTitle);
		 * builder.setPositiveButton(R.string.relieve_confirm, new
		 * android.content.DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * alertDialog.dismiss(); }
		 * 
		 * }); if (alertDialog == null) alertDialog = builder.create();
		 * alertDialog.show();
		 */
	}

	@Override
	protected void onStart() {
		super.onStart();
		myBankList();
	}

	@Override
	protected void onDestroy() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (alertDialog != null) {
			alertDialog.cancel();
			alertDialog = null;
		}
		super.onDestroy();
	}

	/**
	 * 解除银行卡
	 */
	public void relieveBank(String cardId) {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "解绑中，请耐心等待...");
		KkdHttpMagager.getInstance().getDeleteMyBnkManager(cardId,
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							int isBoundBankCard = data
									.getInt("isBoundBankCard");
							PreferenceUtils.getInstance().setBoundBankCard(
									MyBlockActivity.this, isBoundBankCard);
							handler.sendEmptyMessage(RELIEVEBANK_CODE_ZERO);
							handler.sendEmptyMessage(CLOSE_PROGRESSDIALOG);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						handler.sendEmptyMessage(CLOSE_PROGRESSDIALOG);
						if (statusCode == 246) {
							showDialog1();
						} else {
							AppUtil.makeToastForCustomer(MyBlockActivity.this,
									desc);
						}
					}
				});
	}
}
